package com.fmjava.service_upload.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.fmjava.service_upload.config.AppConfig;
import com.fmjava.service_upload.service.UploadService;
import org.apache.commons.lang3.RandomStringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.InputStream;

/*
 *@ClassName UploadServiceImpl
 *@Description TODO
 *@Author 吃麻椒的花酱
 *@Date 2021/7/7 15:58
 *@Version 1.0
 */
@Service
public class UploadServiceImpl implements UploadService {
    String endpoint= AppConfig.ENDPOINT;
    String accessKeyId=AppConfig.ASSESS_KEY_ID;
    String accessKeySecret=AppConfig.ASSESS_KEY_SECRET;
    String bucketName=AppConfig.BUCKET_NAME;

    // 创建OSSClient实例。

    @Override
    public String uploadFile(MultipartFile file) {
        OSS ossClient=null;
        try {
          ossClient=new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            InputStream inputStream =file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String filename= RandomStringUtils.randomAlphanumeric(6)+originalFilename.substring(originalFilename.indexOf('.'));
            String date = new DateTime().toString("yyyy/MM/dd");
            String fileName=date+"/"+filename;
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(bucketName, fileName, inputStream);

            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return  url;
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        return null;


    }

    @Override
    public void deleteFile(String url) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        System.out.println(url+"---------------");
        String filePath=url.substring(48);
        System.out.println(filePath);
        ossClient.deleteObject(bucketName, filePath);
        ossClient.shutdown();
    }
}
